﻿using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Contracts.Core.Enums;
using ZhonTai.Industry.Contracts.Model.Dic;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.DeviceFormula;
using ZhonTai.Industry.Domain.PLCBlock;
using ZhonTai.Industry.Domain.ProductModel;
using ZhonTai.Industry.Domain.StationFeature;
using ZhonTai.Industry.Repositories.DeviceFormula;
using ZhonTai.Industry.Repositories.PLCBlock;
using ZhonTai.Industry.Repositories.StationFeature;
using ZhonTai.Industry.Services.ProductModel.Dto.Input;
using ZhonTai.Industry.Services.ProductModel.Dto.Output;

namespace ZhonTai.Industry.Services.ProductModel
{
    /// <summary>
    /// 产品型号服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class ProductModelService : BaseService, IProductModelService, IDynamicApi
    {
        private readonly IProductModelRepository _productModelRepository;
        public IStationFeatureRepository stationFeatureRepository => LazyGetRequiredService<IStationFeatureRepository>();
        public IDeviceFormulaRepository deviceFormulaRepository => LazyGetRequiredService<IDeviceFormulaRepository>();
        public IPLCBlockRepository plcBlockRepository => LazyGetRequiredService<IPLCBlockRepository>();
        public MesInit.MesInit mesInit => LazyGetRequiredService<MesInit.MesInit>();

        public ProductModelService(IProductModelRepository productModelRepository)
        {
            _productModelRepository = productModelRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ProductModelGetOutput> GetAsync(long id)
        {
            return await _productModelRepository.Select
                .WhereDynamic(id)
                .ToOneAsync<ProductModelGetOutput>();
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<ProductModelGetListOutput>> GetListAsync(ProductModelGetListInput input)
        {
            var list = await _productModelRepository.Select
                .OrderBy(a => a.Sort)
                .ToListAsync<ProductModelGetListOutput>();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ProductModelGetPageOutput>> GetPageAsync(PageInput<ProductModelGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _productModelRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.ProductSeriesId.HasValue && filter.ProductSeriesId > 0, x => filter.ProductSeriesId == x.ProductSeriesId)
                .Include(x => x.ProductRoute)
                .Include(x => x.ProductSeries)
                .Include(x => x.DeviceFormula)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(x => new ProductModelGetPageOutput()
            {
                FormulaOrder = x.DeviceFormula.FormulaOrder,
                SeriesName = x.ProductSeries.SeriesName,
                RouteOrder = x.ProductRoute.RouteOrder
            });
            var data = new PageOutput<ProductModelGetPageOutput>()
            {
                List = list,
                Total = total
            };
            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(ProductModelAddInput input)
        {
            var entity = Mapper.Map<ProductModelEntity>(input);
            var id = (await _productModelRepository.InsertAsync(entity)).Id;
            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(ProductModelUpdateInput input)
        {
            var entity = await _productModelRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("产品型号不存在！");
            }

            Mapper.Map(input, entity);
            await _productModelRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _productModelRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _productModelRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _productModelRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(ProductModelSetEnableInput input)
        {
            var entity = await _productModelRepository.GetAsync(input.ProductModelId);
            entity.Enabled = input.Enabled;
            await _productModelRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 下发设备配方
        /// </summary>
        /// <returns></returns>
        public async Task IssueFormulaOrderAsync(ProductModeIssueFormulaOrderInput input)
        {
            var deviceFormulaEntity = await deviceFormulaRepository.Select.Where(w => w.Id == input.DeviceFormulaId).ToOneAsync();
            if (deviceFormulaEntity == null)
            {
                throw ResultOutput.Exception("设备配方信息不存在！");
            }
            List<StationFeatureEntity> stationFeatures = stationFeatureRepository.Select
                    .Where(w => w.FeatureId == 60000000000004 && w.Enabled)
                    .Include(y => y.WorkStation)
                    .ToList();
            if (stationFeatures.Count == 0 || stationFeatures == null)
            {
                throw ResultOutput.Exception("未发现开启设备配方下发功能！");
            }
            foreach (var s in stationFeatures)
            {
                var currentDevice = InstanceDic.PLC[s.StationId];
                var entity = await plcBlockRepository.Select.Where(w => w.WorkStationId == s.StationId && w.BlockType == DataBlockEnum.MES).ToOneAsync();
                await currentDevice.WriteAsync("DB" + entity.Address + ".4", (short)(deviceFormulaEntity.FormulaOrder));
                await Task.Delay(350);
                await currentDevice.WriteAsync("DB" + entity.Address + ".6", (short)1);
            }
        }

        /// <summary>
        /// 设置最新产品路线
        /// </summary>
        /// <returns></returns>
        public async Task SetLastProductRouteAsync()
        {
            await mesInit.InitProductDataAsync();
        }
    }
}